package com.jhf.skypac_pda;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.elvishew.xlog.XLog;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.dialog.entity.DialogMenuItem;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.guanaj.easyswipemenulibrary.EasySwipeMenuLayout;
import com.jhf.skypac_pda.EventMessage.MessageEvent;
import com.jhf.skypac_pda.base.BaseActivity;
import com.jhf.skypac_pda.db.bean.DB_OperationRecord;
import com.jhf.skypac_pda.db.impl.OperationRecordDaoImp;
import com.jhf.skypac_pda.model.DialogCallback;
import com.jhf.skypac_pda.model.FeedRecord;
import com.jhf.skypac_pda.model.FinishedProductModel;
import com.jhf.skypac_pda.model.LzyResponse;
import com.jhf.skypac_pda.model.LzyResponse2;
import com.jhf.skypac_pda.model.StockRegionModel;
import com.jhf.skypac_pda.model.StockLocationModel;
import com.jhf.skypac_pda.utils.PrefUtils;
import com.jhf.skypac_pda.utils.Urls;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.barcode.BarcodeManager;
import com.symbol.emdk.barcode.ScanDataCollection;
import com.symbol.emdk.barcode.Scanner;
import com.symbol.emdk.barcode.ScannerConfig;
import com.symbol.emdk.barcode.ScannerException;
import com.symbol.emdk.barcode.ScannerInfo;
import com.symbol.emdk.barcode.ScannerResults;
import com.symbol.emdk.barcode.StatusData;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okgo.OkGo;
import okgo.model.HttpHeaders;
import okgo.model.Response;
import okhttp3.RequestBody;

import static com.jhf.skypac_pda.utils.ConstantPara.JSON;

public class FinishedProductStockInActivity extends BaseActivity implements EMDKManager.EMDKListener, Scanner.DataListener, Scanner.StatusListener, BarcodeManager.ScannerConnectionListener {
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.ll_empty)
    LinearLayout imgEmpty;
    @BindView(R.id.et_fragment_search)
    EditText etFragmentSearch;
    @BindView(R.id.et_warehouse)
    TextView etWarehouse;
    @BindView(R.id.et_warehouse_area)
    TextView etWarehouseArea;
    @BindView(R.id.et_warehouse_position)
    TextView etWarehousePosition;

    private List<FinishedProductModel> mList = new ArrayList<>();
    private FinishedProductListAdapter mAdapter;

    private AtomicBoolean initFlag = new AtomicBoolean(false);
    private EMDKManager emdkManager = null;
    private BarcodeManager barcodeManager = null;
    private Scanner scanner = null;
    public ScannerInfo readScannerInfo;
    private boolean bSoftTriggerSelected = false;
    private boolean bExtScannerDisconnected = false;
    private final Object lock = new Object();

    private FinishedProductModel finishedProductModel = new FinishedProductModel();
    private ArrayList<DialogMenuItem> stringItems = new ArrayList<>();
    private ArrayList<DialogMenuItem> stringLocationItems = new ArrayList<>();
    private ArrayList<StockRegionModel> stockRegionModels = new ArrayList<>();
    private ArrayList<StockLocationModel> stockLocationModels = new ArrayList<>();
    private int stockRegionPosition = 0;
    private int stockLocationPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finished_product_stock_in);
        ButterKnife.bind(this);
        //initZebra(this);
        initView();
    }

    private void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvData.setLayoutManager(manager);
        mAdapter = new FinishedProductListAdapter(R.layout.stock_in_item_rv_swipemenu, mList);
        rvData.setAdapter(mAdapter);
        //rvData.setPullRefreshEnabled(false);

        etFragmentSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!etFragmentSearch.getText().toString().trim().equals("")) {
                        getInputStockOrderByCode(etFragmentSearch.getText().toString().trim());
                    }
                }
                return false;
            }
        });
    }

    @OnClick({R.id.ll_search, R.id.et_warehouse, R.id.et_warehouse_area, R.id.et_warehouse_position, R.id.tv_back, R.id.sign_in_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_warehouse:
                break;
            case R.id.et_warehouse_area:
                final ActionSheetDialog dialog = new ActionSheetDialog(FinishedProductStockInActivity.this, stringItems, null);
                dialog.title("选择库区")//
                        .titleTextSize_SP(14.5f)//
                        .show();

                dialog.setOnOperItemClickL(new OnOperItemClickL() {
                    @Override
                    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                        //T.showShort(mContext, stringItems[position]);
                        etWarehouseArea.setText(stringItems.get(position).mOperName);
                        stockRegionPosition = position;

                        getInputStockLocation(finishedProductModel.getStockRoomCode(), stockRegionModels.get(position).getStockRegionCode());

                        dialog.dismiss();
                    }
                });
                break;
            case R.id.et_warehouse_position:
                final ActionSheetDialog dialog2 = new ActionSheetDialog(FinishedProductStockInActivity.this, stringLocationItems, null);
                dialog2.title("选择库位")//
                        .titleTextSize_SP(14.5f)//
                        .show();

                dialog2.setOnOperItemClickL(new OnOperItemClickL() {
                    @Override
                    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                        //T.showShort(mContext, stringItems[position]);
                        etWarehousePosition.setText(stringLocationItems.get(position).mOperName);
                        stockLocationPosition = position;

                        //getInputStockLocation(etWarehouse.getText().toString().trim(), stockRegionModels.get(position).getStockRegionCode());

                        dialog2.dismiss();
                    }
                });
                break;
            case R.id.ll_search:
                if (!etFragmentSearch.getText().toString().trim().equals("")) {
                    getInputStockOrderByCode(etFragmentSearch.getText().toString().trim());
                }
                break;
            case R.id.tv_back:
                finish();
                break;
            case R.id.sign_in_button:
                signIn();
                break;
        }
    }

    public void initZebra(Context context) {
        boolean initResult = initFlag.compareAndSet(false, true);
        if (initResult) {
            XLog.i("ZEBRA初始化扫码设备");
            try {
                EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
                XLog.i("ZEBRA初始化结果" + results.statusCode);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            XLog.i("ZEBRA已经初始化");
        }

    }

    @Override
    public void onOpened(EMDKManager emdkManager) {
        this.emdkManager = emdkManager;
        // Acquire the barcode manager resources
        initBarcodeManager();
        // Enumerate scanner devices
        enumerateScannerDevices();
    }

    @Override
    public void onClosed() {
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
        }
    }

    private void initScanner() {
        if (scanner == null) {
            if (barcodeManager != null) {
                scanner = barcodeManager.getDevice(readScannerInfo);
                setDecoders();
            }
            if (scanner != null) {
                scanner.addDataListener(this);
                scanner.addStatusListener(this);
                try {
                    scanner.enable();
                } catch (ScannerException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initBarcodeManager() {
        barcodeManager = (BarcodeManager) emdkManager.getInstance(EMDKManager.FEATURE_TYPE.BARCODE);
        // Add connection listener
        if (barcodeManager != null) {
            barcodeManager.addConnectionListener(this);
        }
    }

    private void deInitBarcodeManager() {
        if (emdkManager != null) {
            emdkManager.release(EMDKManager.FEATURE_TYPE.BARCODE);
        }
    }

    private void deInitScanner() {
        if (scanner != null) {
            try {
                scanner.disable();
                scanner.removeDataListener(this);
                scanner.removeStatusListener(this);
                scanner.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
            scanner = null;
        }
    }

    private void setDecoders() {
        if (scanner != null) {
            try {
                ScannerConfig config = scanner.getConfig();
                // Set EAN8
                config.decoderParams.ean8.enabled = true;
                // Set EAN13
                config.decoderParams.ean13.enabled = true;
                // Set Code39
                config.decoderParams.code39.enabled = true;
                //Set Code128
                config.decoderParams.code128.enabled = true;
                scanner.setConfig(config);
            } catch (ScannerException e) {
                e.printStackTrace();
            }
        }
    }

    private void enumerateScannerDevices() {
        if (barcodeManager != null) {
            List<ScannerInfo> deviceList = barcodeManager.getSupportedDevicesInfo();
            XLog.i("enumerateScannerDevices size = " + deviceList.size());
            if ((deviceList != null) && (deviceList.size() != 0)) {
                Iterator<ScannerInfo> it = deviceList.iterator();
                while (it.hasNext()) {
                    ScannerInfo scnInfo = it.next();
                    XLog.i("scnInfo friendlyName=%s,isDefaultScanner=%s", scnInfo.getFriendlyName(), scnInfo.isDefaultScanner());
                    if (scnInfo.isDefaultScanner()) {
                        readScannerInfo = scnInfo;
                        deInitScanner();
                        initScanner();
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void onConnectionChange(ScannerInfo scannerInfo, BarcodeManager.ConnectionState connectionState) {
        String scannerName = "";
        String scannerNameExtScanner = scannerInfo.getFriendlyName();
        scannerName = scannerInfo.getFriendlyName();
        if (scannerName.equalsIgnoreCase(scannerNameExtScanner)) {
            switch (connectionState) {
                case CONNECTED:
                    bSoftTriggerSelected = false;
                    synchronized (lock) {
                        initScanner();
                        bExtScannerDisconnected = false;
                    }
                    break;
                case DISCONNECTED:
                    bExtScannerDisconnected = true;
                    synchronized (lock) {
                        deInitScanner();
                    }
                    break;
            }
        } else {
            bExtScannerDisconnected = false;
        }
    }

    @Override
    public void onData(ScanDataCollection scanDataCollection) {
        //if (FinishedProductStockInActivity.this.getWindow().getDecorView().getVisibility() == View.VISIBLE) {
            if ((scanDataCollection != null) && (scanDataCollection.getResult() == ScannerResults.SUCCESS)) {
                ArrayList<ScanDataCollection.ScanData> scanData = scanDataCollection.getScanData();
                for (ScanDataCollection.ScanData data : scanData) {
                    XLog.i("扫码结果data = %s,type=%s", data.getData(), data.getLabelType());
                    //activity.handleQrCode(data.getData());

                    //当前扫码返回的是卷号或者是库位，如何区分？卷号优先，库位次之

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (etFragmentSearch.getText().toString().equals("")) {
                                etFragmentSearch.setText(data.getData());
                                getInputStockOrderByCode(data.getData());
                            } else {
                                //这时认为扫码的是库位，然后去判断库位是否是合法的（是否已加载，是否是存在的）
                                if (stockLocationModels == null || stockLocationModels.size() == 0) {
                                    Toast.makeText(FinishedProductStockInActivity.this, "请先选择库区", Toast.LENGTH_SHORT).show();
                                    return;
                                } else {
                                    for (int i = 0; i < stockLocationModels.size(); i++) {
                                        if (data.getData().equals(stockLocationModels.get(i).getStockLocationCode())) {
                                            etWarehousePosition.setText(stockLocationModels.get(i).getStockLocationName());
                                            stockLocationPosition = i;
                                            return;
                                        } else {
                                            continue;
                                        }
                                    }

                                    Toast.makeText(FinishedProductStockInActivity.this, "没有所在库区的库位", Toast.LENGTH_SHORT).show();
                                }
                            }

                        }
                    });
                //}
            }
        }
    }

    @Override
    public void onStatus(StatusData statusData) {
        StatusData.ScannerStates state = statusData.getState();
        switch (state) {
            case IDLE:
                // set trigger type
                if (bSoftTriggerSelected) {
                    scanner.triggerType = Scanner.TriggerType.SOFT_ONCE;
                    bSoftTriggerSelected = false;
                } else {
                    scanner.triggerType = Scanner.TriggerType.HARD;
                }
                // submit read
                if (!scanner.isReadPending() && !bExtScannerDisconnected) {
                    try {
                        scanner.read();
                    } catch (ScannerException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case WAITING:
                break;
            case SCANNING:
                break;
            case DISABLED:
                break;
            case ERROR:
                break;
            default:
                break;
        }
    }

    public class FinishedProductListAdapter extends BaseQuickAdapter<FinishedProductModel, BaseViewHolder> {


        public FinishedProductListAdapter(@LayoutRes int layoutResId, @Nullable List<FinishedProductModel> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(final BaseViewHolder helper, FinishedProductModel item) {
            helper.setText(R.id.textViewRollNumber, item.getMaterialBatchCode());
            helper.setText(R.id.textViewMaterialNumber, item.getMaterialCode());
            helper.setText(R.id.textViewProductName, item.getMaterialName());
            helper.setText(R.id.textViewSpecification, item.getMaterialSpec());
            helper.setText(R.id.textViewWeight, item.getProductionReportNetWeight() + " Kg");
            helper.setText(R.id.textViewLength, item.getProductionReportLength() + " m");
            helper.getView(R.id.left).setVisibility(View.GONE);
            helper.getView(R.id.right_menu_2).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(FinishedProductStockInActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    deleteItem(item);

                    EasySwipeMenuLayout easySwipeMenuLayout = helper.getView(R.id.es);
                    easySwipeMenuLayout.resetStatus();
                }
            });
            /*helper.getView(R.id.content).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(FinishedProductStockInActivity.this, "setOnClickListener", Toast.LENGTH_SHORT).show();

                }
            });*/

        }

    }

    private void deleteItem(FinishedProductModel item) {
        // 从数据源中删除数据
        int position = mAdapter.getData().indexOf(item);
        mAdapter.getData().remove(item);
        mAdapter.notifyItemRemoved(position); // 通知数据源改变

        etFragmentSearch.setText("");
        etWarehouse.setText("");
        etWarehouseArea.setText("");
        etWarehousePosition.setText("");
    }

    private void getInputStockOrderByCode(String data) {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<FinishedProductModel>>get(Urls.URL_GET_INPUT_STOCK_INFO + data)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse<FinishedProductModel>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<FinishedProductModel>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                finishedProductModel = response.body().data;
                                finishedProductModel.setMaterialBatchCode(data);
                                if (response.body().data.getStockIoOrderStatus().equals("new")) {
                                    etWarehouse.setText(finishedProductModel.getStockRoomName());
                                    mList.clear();
                                    mList.add(finishedProductModel);
                                    mAdapter.notifyDataSetChanged();

                                    getInputStockRegion(finishedProductModel.getStockRoomCode());
                                } else {
                                    deInitScanner();
                                    deInitBarcodeManager();
                                    if (emdkManager != null) {
                                        emdkManager.release();
                                        emdkManager = null;
                                        initFlag.set(false);
                                    }

                                    etFragmentSearch.setText("");
                                    etWarehouse.setText("");
                                    etWarehouseArea.setText("");
                                    etWarehousePosition.setText("");
                                    mList.clear();
                                    mAdapter.notifyDataSetChanged();
                                    Intent intent = new Intent(FinishedProductStockInActivity.this, UpdateStockInActivity.class);
                                    intent.putExtra("finishedProductModel", (Serializable) finishedProductModel);
                                    //intent.putExtra("rollNum", data);
                                    startActivity(intent);
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<FinishedProductModel>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(), Toast.LENGTH_SHORT).show();
                        etFragmentSearch.setText("");
                        etWarehouse.setText("");
                        etWarehouseArea.setText("");
                        etWarehousePosition.setText("");
                        mList.clear();
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }

    private void getInputStockRegion(String stockRoomCode) {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse2<ArrayList<StockRegionModel>>>get(Urls.URL_GET_STOCK_REGION + "?pageNum=" + 1 + "&pageSize=" + 1000 + "&stockRoomCode=" + stockRoomCode)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse2<ArrayList<StockRegionModel>>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse2<ArrayList<StockRegionModel>>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                stockRegionModels = response.body().rows;
                                stringItems.clear();
                                for (StockRegionModel stockRegionModel :
                                        stockRegionModels) {
                                    DialogMenuItem dialogMenuItem = new DialogMenuItem(stockRegionModel.getStockRegionName(), 0);
                                    stringItems.add(dialogMenuItem);
                                }

                                /*finishedProductModel = response.body().data;
                                finishedProductModel.setMaterialBatchCode(data);
                                if (response.body().data.getStockIoOrderStatus().equals("approved")) {
                                    etWarehouse.setText(finishedProductModel.getStockRoomName());
                                    mList.clear();
                                    mList.add(finishedProductModel);
                                    if (null == mList || mList.size() == 0) {
                                        imgEmpty.setVisibility(View.VISIBLE);
                                    } else {
                                        imgEmpty.setVisibility(View.GONE);
                                        mAdapter.notifyDataSetChanged();
                                    }
                                } else {
                                    Intent intent = new Intent(FinishedProductStockInActivity.this, UpdateStockInActivity.class);
                                    intent.putExtra("finishedProductModel", (Serializable) finishedProductModel);
                                    //intent.putExtra("rollNum", data);
                                    startActivity(intent);
                                }*/
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse2<ArrayList<StockRegionModel>>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

        private void getInputStockLocation(String stockRoomCode, String stockRegionCode){
            HttpHeaders headers = new HttpHeaders();
            headers.put("Authorization", PrefUtils.getString(this, "token", ""));
            OkGo.<LzyResponse2<ArrayList<StockLocationModel>>>get(Urls.URL_GET_STOCK_LOCATION + "?pageNum=" + 1 + "&pageSize=" + 1000 + "&stockRoomCode=" + stockRoomCode + "&stockRegionCode=" + stockRegionCode)
                    .tag(this)
                    .headers(headers)
                    .execute(new DialogCallback<LzyResponse2<ArrayList<StockLocationModel>>>(this) {
                        @Override
                        public void onSuccess(Response<LzyResponse2<ArrayList<StockLocationModel>>> response) {
                            if (null != response.body().msg) {
                                if (response.body().msg.contains("成功")) {
                                    stockLocationModels = response.body().rows;
                                    stringLocationItems.clear();
                                    for (StockLocationModel stockLocationModel :
                                            stockLocationModels) {
                                        DialogMenuItem dialogMenuItem = new DialogMenuItem(stockLocationModel.getStockLocationName(), 0);
                                        stringLocationItems.add(dialogMenuItem);
                                    }

                                    //清空之前选择的库位
                                    etWarehousePosition.setText("");

                                /*finishedProductModel = response.body().data;
                                finishedProductModel.setMaterialBatchCode(data);
                                if (response.body().data.getStockIoOrderStatus().equals("approved")) {
                                    etWarehouse.setText(finishedProductModel.getStockRoomName());
                                    mList.clear();
                                    mList.add(finishedProductModel);
                                    if (null == mList || mList.size() == 0) {
                                        imgEmpty.setVisibility(View.VISIBLE);
                                    } else {
                                        imgEmpty.setVisibility(View.GONE);
                                        mAdapter.notifyDataSetChanged();
                                    }
                                } else {
                                    Intent intent = new Intent(FinishedProductStockInActivity.this, UpdateStockInActivity.class);
                                    intent.putExtra("finishedProductModel", (Serializable) finishedProductModel);
                                    //intent.putExtra("rollNum", data);
                                    startActivity(intent);
                                }*/
                                }
                            }
                        }

                        @Override
                        public void onError(Response<LzyResponse2<ArrayList<StockLocationModel>>> response) {
                            Toast.makeText(getApplicationContext(), response.getException().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });

    }

    private void signIn() {
        if(TextUtils.isEmpty(etFragmentSearch.getText().toString().trim())){

            Toast.makeText(FinishedProductStockInActivity.this, "卷号不能为空",Toast.LENGTH_SHORT).show();

            return ;
        }

        if(TextUtils.isEmpty(etWarehouse.getText().toString().trim())){

            Toast.makeText(FinishedProductStockInActivity.this, "仓库不能为空",Toast.LENGTH_SHORT).show();

            return ;
        }
        if(TextUtils.isEmpty(etWarehouseArea.getText().toString().trim())){

            Toast.makeText(FinishedProductStockInActivity.this, "库区不能为空",Toast.LENGTH_SHORT).show();

            return ;
        }
        if(TextUtils.isEmpty(etWarehousePosition.getText().toString().trim())){

            Toast.makeText(FinishedProductStockInActivity.this, "库位不能为空",Toast.LENGTH_SHORT).show();

            return ;
        }

        final NormalDialog dialog3 = new NormalDialog(FinishedProductStockInActivity.this);
        dialog3.content("是否确认入库？")
                .btnNum(2)
                .btnText("取消", "确认")
                .title("入库确认")
                //.showAnim(mBasIn)//
                //.dismissAnim(mBasOut)//
                .show();
        dialog3.setCanceledOnTouchOutside(false);

        dialog3.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog3.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog3.dismiss();
                        Map<String ,Object> map=new HashMap<>();
                        map.put("stockIoOrderId", finishedProductModel.getStockIoOrderId());
                        map.put("productionRecordCode", finishedProductModel.getProductionRecordCode());
                        map.put("stockRoomCode", finishedProductModel.getStockRoomCode());
                        map.put("stockRegionCode", stockRegionModels.get(stockRegionPosition).getStockRegionCode());
                        map.put("stockLocationCode", stockLocationModels.get(stockLocationPosition).getStockLocationCode());
                        Gson gg=new Gson();
                        String json =gg.toJson(map);

                        RequestBody body = RequestBody.create(JSON, json);
                        HttpHeaders headers = new HttpHeaders();
                        headers.put("Authorization", PrefUtils.getString(FinishedProductStockInActivity.this, "token", ""));
                        OkGo.<LzyResponse<String>>post(Urls.URL_POST_STOCK_IN_CONFIRM)
                                .tag(this)
                                .upRequestBody(body)
                                .isMultipart(false)
                                .headers(headers)
                                .execute(new DialogCallback<LzyResponse<String>>(FinishedProductStockInActivity.this) {
                                    @Override
                                    public void onSuccess(Response<LzyResponse<String>> response) {
                                        if (null != response.body().msg) {
                                            if (response.body().msg.contains("成功")) {
                                                Toast.makeText(getApplicationContext(), "入库成功",Toast.LENGTH_SHORT).show();
                                                finish();
                                            }
                                        }
                                    }

                                    @Override
                                    public void onError(Response<LzyResponse<String>> response) {
                                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                                    }
                                });
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShutDown(MessageEvent eventMsg) {
        String msg = eventMsg.getMessage();
        if (eventMsg.getType() == 8) {
            // activity关闭，从栈中移除
            //appManager.finishActivity(this);
            if (FinishedProductStockInActivity.this.getWindow().getDecorView().getVisibility() == View.VISIBLE) {
                Toast.makeText(this, "登录已过期", Toast.LENGTH_SHORT).show();
                Log.i("登录过期走到这里=========", "FeedingDetailActivity");
                Intent intent = new Intent(FinishedProductStockInActivity.this, LoginActivity.class);
                intent.putExtra("isUpdate", true);
                startActivity(intent);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        deInitScanner();
        deInitBarcodeManager();
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
            initFlag.set(false);
        }
    }

    @Override
    protected void onResume() {
        // The application is in foreground
        super.onResume();
        /*new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                initZebra(FinishedProductStockInActivity.this);
            }
        }, 5000);*/

        initZebra(FinishedProductStockInActivity.this);
    }

    /*@Override
    protected void onPause() {
        // The application is in background
        // Release the barcode manager resources
        super.onPause();
        deInitScanner();
        deInitBarcodeManager();
    }*/
}
